package com.kedll.library.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.view.View;

import com.kedll.library.adapter.WrapAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by QiQi on 2017/1/23.
 */

public class WrapRecyclerView extends RecyclerView {
    List<View> headViewList = new ArrayList<>();
    List<View> footViewList = new ArrayList<>();

    boolean shouldAdjustSpanSize;

    WrapAdapter mWrapAdapter;

    private OnScrollListener onScrollListener;

    private OnLoadMoreDataListener onLoadMoreDataListener;

    public void setOnLoadMoreDataListener(OnLoadMoreDataListener onLoadMoreDataListener) {
        this.onLoadMoreDataListener = onLoadMoreDataListener;
    }

    public void setScrollListener(OnScrollListener onScrollListener) {
        this.onScrollListener = onScrollListener;
    }

    public WrapRecyclerView(Context context) {
        super(context);
    }

    public WrapRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);


        setOnScrollListener(new OnScrollListener() {
            /**
             * 最后一个可见的item的位置
             */
            private int lastVisibleItemPosition;

            /**
             * 当前滑动的状态
             */
            private int currentScrollState = 0;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
                if (onScrollListener != null) {
                    onScrollListener.onScrolled(recyclerView, dx, dy);
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (onScrollListener != null) {
                    onScrollListener.onScrollStateChanged(recyclerView, newState);
                }
                currentScrollState = newState;
                LayoutManager layoutManager = recyclerView.getLayoutManager();
                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                if ((visibleItemCount > 0 && currentScrollState == RecyclerView.SCROLL_STATE_IDLE) && (lastVisibleItemPosition >= totalItemCount - 1)) {
                    //滚动到底部
                    setFooterVisibility(true);
                    if (onLoadMoreDataListener != null) {
                        onLoadMoreDataListener.onLoadMore();
                    }
                }
            }
        });
    }

    @Override
    public void setAdapter(Adapter adapter) {
        if (adapter instanceof WrapAdapter) {
            mWrapAdapter = (WrapAdapter) adapter;
            super.setAdapter(adapter);
        } else {
            mWrapAdapter = new WrapAdapter(adapter);
            for (View v : headViewList) {
                mWrapAdapter.addHeadView(v);
            }
            if (headViewList.size() > 0) {
                headViewList.clear();
            }

            for (View v : footViewList) {
                mWrapAdapter.addFootView(v);
            }
            if (footViewList.size() > 0) {
                footViewList.clear();
            }

            super.setAdapter(mWrapAdapter);
        }

        if (shouldAdjustSpanSize) {
            mWrapAdapter.adjustSpanSize(this);
        }

        try {
            if (getWrappedAdapter().hasObservers())
                getWrappedAdapter().unregisterAdapterDataObserver(mDataObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }

        getWrappedAdapter().registerAdapterDataObserver(mDataObserver);
        mDataObserver.onChanged();
    }


    @Override
    public WrapAdapter getAdapter() {
        return mWrapAdapter;
    }

    public Adapter getWrappedAdapter() {
        if (mWrapAdapter == null) {
            throw new IllegalStateException("You must set an adapter before");
        }
        return mWrapAdapter.getWrappedAdapter();
    }

    public void addHeadView(View headView) {
        if (headView == null) {
            return;
        }
        if (mWrapAdapter == null) {
            headViewList.add(headView);
        } else {
            mWrapAdapter.addHeadView(headView);
        }
    }

    public void addFootView(View footView) {
        if (footView == null) {
            return;
        }
        if (mWrapAdapter == null) {
            footViewList.add(footView);
        } else {
            mWrapAdapter.addFootView(footView);
        }
    }

    @Override
    public void setLayoutManager(LayoutManager layout) {
        super.setLayoutManager(layout);
        if (layout instanceof GridLayoutManager || layout instanceof StaggeredGridLayoutManager) {
            this.shouldAdjustSpanSize = true;
        }
    }

    public int getHeadCount() {
        if (mWrapAdapter == null) {
            throw new IllegalStateException("You must set an adapter before");
        }
        return mWrapAdapter.getHeadCount();
    }

    public int getFootCount() {
        if (mWrapAdapter == null) {
            throw new IllegalStateException("You must set an adapter before");
        }
        return mWrapAdapter.getFootCount();
    }

    public void setFooterVisibility(boolean shouldShow) {
        if (mWrapAdapter == null) {
            throw new IllegalStateException("You must set an adapter before");
        }
        mWrapAdapter.setFooterVisibility(shouldShow);
    }

    private final AdapterDataObserver mDataObserver = new AdapterDataObserver() {
        @Override
        public void onChanged() {
            if (mWrapAdapter != null) {
                mWrapAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            mWrapAdapter.notifyItemRangeChanged(positionStart, itemCount);
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
            mWrapAdapter.notifyItemRangeChanged(positionStart, itemCount, payload);
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            mWrapAdapter.notifyItemRangeInserted(positionStart, itemCount);
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
            mWrapAdapter.notifyItemRangeRemoved(fromPosition, toPosition);
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            mWrapAdapter.notifyItemRangeRemoved(positionStart, itemCount);
        }
    };

    public interface OnLoadMoreDataListener {
        void onLoadMore();
    }
}
